package com.hankol.material

import android.graphics.Typeface
import android.util.TypedValue
import android.view.LayoutInflater
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.activity.BaseFragment
import com.baselibrary.bean.download.DownloadInfo
import com.baselibrary.db.DBManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.FileUtils
import com.baselibrary.utils.SpUtils
import com.baselibrary.utils.StorageQueryUtil
import com.google.android.material.tabs.TabLayout
import com.hankol.material.adapter.HomePagerAdapter
import com.hankol.material.databinding.ActivityMaterialDownloadMainBinding
import com.hankol.material.fragment.DownloadCompleteFragment
import com.hankol.material.fragment.DownloadingFragment
import com.hankol.material.limit.DownloadLimitManager.FILE_PATH
import com.hankol.material.viewmodel.DownloadMainViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**下载列表：
 * 下载中
 * 下载完成
 * @author: merbng
 * @time: 2021/10/15 10:02
 * @description:
 */
@Route(path = ActivityRouter.MATERIAL.MATERIAL_DOWNLOAD_MAIN)
class DownloadMainActivity : BaseActivity() {
    private lateinit var viewModel: DownloadMainViewModel
    private lateinit var binding: ActivityMaterialDownloadMainBinding
    val mAdapter: HomePagerAdapter by lazy { HomePagerAdapter(supportFragmentManager) }

    override fun getLayoutId(): Int {
        return R.layout.activity_material_download_main
    }

    val userIds: Int by lazy { SpUtils.getInstance().userId}
    var pos = 0
    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        setStatusBarDarkTheme(false)
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(DownloadMainViewModel::class.java)
        if (intent.hasExtra(Constants.KEY_SWITCH_POS)) {
            pos = intent.getIntExtra(Constants.KEY_SWITCH_POS, 0)
        }
        binding.backImageView.setOnClickListener { finish() }
        val listData = setTablayoutTitleData()
        val fragmentList = mutableListOf<BaseFragment>()
        fragmentList.add(DownloadingFragment.newInstance())
        fragmentList.add(DownloadCompleteFragment.newInstance())
        mAdapter.fragments = fragmentList
        binding.viewPager.adapter = mAdapter
        binding.viewPager.offscreenPageLimit = listData.size
        binding.tabLayout.setupWithViewPager(binding.viewPager)
        mAdapter.setData(listData)
        binding.viewPager.setCurrentItem(pos)
        getMemory()
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                tab.setCustomView(null);//恢复到 默认
            }

            override fun onTabSelected(tab: TabLayout.Tab) {
                val textView = LayoutInflater.from(this@DownloadMainActivity).inflate(R.layout.tab_item, null) as TextView
                textView.setTextColor(getResources().getColor(R.color.white));
                textView.setText(tab.getText());
                textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16f)
                textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                tab.setCustomView(textView);
            }
        })
        binding.tvCache.setOnClickListener {
            FileUtils.openAssignFolder(this, FILE_PATH)
        }
    }

    private fun setTablayoutTitleData(): ArrayList<String> {
        val listData = ArrayList<String>()
        val downloadList = DBManager.getInstance().getDownloadList(userIds, false)
        val list = mutableListOf<DownloadInfo>()
        for (file in downloadList) {
            if (file.downloadStatus.equals(DownloadInfo.DOWNLOAD) || file.downloadStatus.equals(DownloadInfo.DOWNLOAD_PAUSE) || file.downloadStatus.equals(DownloadInfo.DOWNLOAD_WAIT)) {
                list.add(file)
            }
        }
        listData.add("下载中 ${if (list.size == 0) "" else list.size}")
        listData.add("已完成")
        return listData
    }

    /**手机剩余空间
     * @author: merbng
     * @time: 2021/11/17 19:37
     * @description:
     */
    private fun getMemory() {
        binding.tvCache.text = "${StorageQueryUtil.queryWithStorageManager(this)}"
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun update(info: DownloadInfo) {
        if (DownloadInfo.DOWNLOAD_OVER.equals(info.getDownloadStatus())) {
            getMemory()
            mAdapter.setData(setTablayoutTitleData())
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_del_material_file || messageBus.codeType == MessageBus.msgId_refresh_capacity || messageBus.codeType == MessageBus.msgId_download_complete) {
            getMemory()
            mAdapter.setData(setTablayoutTitleData())
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}